package com.hjt.gulimall.order.web;

import com.hjt.common.exception.NoStockException;
import com.hjt.gulimall.order.constant.OrderConstant;
import com.hjt.gulimall.order.service.OrderService;
import com.hjt.gulimall.order.vo.OrderConfirmVo;
import com.hjt.gulimall.order.vo.OrderSubmitResponseVo;
import com.hjt.gulimall.order.vo.OrderSubmitVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.jws.WebParam;
import java.util.concurrent.ExecutionException;

/**
 * @author:97007
 * @date:2021/10/9 19:11
 */
@Controller
public class OrderWebController {

    @Autowired
    private OrderService orderService;

    @GetMapping("/toTrade")
    public String toTrade(Model model) throws ExecutionException, InterruptedException {


        // 查询订单确认信息
        OrderConfirmVo orderConfirmVo =  orderService.getOrderConfirmVo();

        model.addAttribute("orderConfirmData", orderConfirmVo);
        return "confirm";
    }

    /**
     * 提交订单
     * @param orderSubmitVo
     * @return
     */
    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo orderSubmitVo, Model model, RedirectAttributes redirectAttributes) {
        try {
            OrderSubmitResponseVo responseVo =  orderService.submitOrder(orderSubmitVo);
            model.addAttribute("response", responseVo);
            if (responseVo.getCode().equals(0)) {
                // 下单成功跳转到支付页
                return "pay";
            } else {
                // 下单失败重新下单
                Integer code = responseVo.getCode();
                if (code.equals(OrderConstant.ORDER_PRICE_VERIFY_FAILED)) {
                    redirectAttributes.addFlashAttribute("msg", "价格校验失败");
                } else if (code.equals(OrderConstant.ORDER_TOKEN_VERIFY_FAILED)) {
                    redirectAttributes.addFlashAttribute("msg", "页面过期，请重新提交订单");
                }
                return "redirect:http://order.gulimall.com/toTrade";
            }
        } catch (NoStockException e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("msg", "库存不足");
            return "redirect:http://order.gulimall.com/toTrade";
        }
    }
}
